<template>
  <div class="node-db-console">
    <Row type="flex">
      <Col :span="4" class="left-box">
      <Selector label="数据源" @selectChange="sourceChange" :path="path.source"></Selector>
      <hr>
      <SelectPanel @select="entityChange" :data="entityList">
        <template slot="option" slot-scope="data">
          <div class="entity-option">
            {{data.item.TABLE_NAME}}
            <span class="type-code">
              {{data.item.TABLE_TYPE}}
            </span>
          </div>
        </template>
      </SelectPanel>
      </Col>
      <Col :span="20" class="right-box">
      <div class="tool-box">
        <Button @click="execute" type="primary" icon="flash" :disabled="!sourceData">执行<span v-if="!sourceData">( 未选择数据源 )</span></Button>
        <Button icon="ios-download" type="info" @click="exportData" :disabled="!resultModel" :loading="exportLoading">导出数据</Button>
        <Button @click="clearSql" type="ghost">清空</Button>
        <Button @click="presetConfigShow" :loading="presetModelLoading" icon="navicon-round" type="success" class="pull-right">预置脚本</Button>
        <!-- 页面内读取选项 暂时弃用
        <Button @click="savePreset" icon="archive" type="success" class="pull-right">保存</Button>
        <Dropdown trigger="custom" :visible="presetVisible" type="success" class="pull-right" placement="bottom-end" v-click-out="presetOutClick">
          <Button type="success" @click="presetVisible=true"> 
            <Icon type="navicon-round"></Icon>
            读取
            <Icon type="arrow-down-b"></Icon>
          </Button>
          <DropdownMenu slot="list"> 
            <DropdownItem v-for="(item,index) in presetList" :name="index" :key="index" @click="selectpresetList(index)" :class="{'preset-select':presetIndex===index}">
              <div @click="selectpresetList(index)">
              <div class="item-name">{{item.name}}
                <span @click.stop="deletePreset(item.id)">
                  <Icon  class="pull-right red delete-sql" type="close"></Icon>
                </span>
              </div>
              <div class="item-code" v-height-light>{{item.code}}</div>
              </div>
            </DropdownItem>
          </DropdownMenu>
        </Dropdown>
        -->
      </div>
      <hr>
      <Input v-show="false" v-model="sqlName" class="name-input">
        <span slot="prepend">描述</span>
      </Input>
      <CodeEditor lang="sql" v-model="sqlString"></CodeEditor>
      <hr>
      <div class="data-box">
        <DataTable v-if="resultModel" ref="dataTable" :data="resultData" :model="resultModel"></DataTable>
      </div>
      </Col>
    </Row>
    <Modal class="modal-full modal-node" width="90%" v-model="presetModal" title="预置脚本">
      <div>
        <GridPanel v-if="presetModel" :model="presetModel"></GridPanel>
      </div>
    </Modal>
  </div>
</template>
<script>
import $ from "@/common";
import DataTable from "@/components/gridTableSample";
import GridPanel from "@/node/gridPanel/index";

import Selector from "@/components/selector";
import SelectPanel from "@/components/selectPanel";
import CodeEditor from "@/element/codeEditor";
import Modal from "@/element/modal";

import HeightLight from "@/directives/height-light";
import ClickOut from "@/directives/click-out";

import { billParser } from "@/common/parser";

var Base64 = require("js-base64").Base64;
export default {
  data() {
    return {
      path: {
        _source: "/service/{app}/pf/rdbs",
        source: "/service/{app}/dataset/data/db_rdb",
        entity: "/service/{app}/pf/rdb/entities/{code}",
        execute: "/service/{app}/dbconsole/execute",
        export: "/service/{app}/dbconsole/export",
        model: "/service/{app}/bill/model/dbconsole_log",
        //preset相关暂时弃用，直接采用gp的方法处理预置数据
        preset: {
          list: "/service/cs/list",
          delete: "/service/cs/list"
        }
      },
      presetVisible: false,
      resultData: [],
      presetList: [],
      presetIndex: null,
      entityList: [],
      resultModel: null,
      entityCode: null,
      sourceData: null,
      sqlString: "",
      executing: false,
      sqlName: "",
      fetchingEntity: false,
      sourceId: null,
      executeSqlString: "",
      exportLoading: false,
      presetModel: null,
      presetModelLoading: false,
      presetModal: false
    };
  },
  methods: {
    presetOutClick() {
      this.presetVisible = false;
    },
    presetConfigShow() {
      if (this.model) {
        this.presetModal = true;
      } else {
        this.presetModelLoading = true;
        $.link(this.path.model)
          .then(res => {
            this.$set(this, "presetModel", billParser(res.data));
            this.presetModal = true;
          })
          .finally(() => {
            this.presetModelLoading = false;
          });
      }
    },
    execute() {
      this.executing = true;
      $.link(this.path.execute, {
        //对执行语句进行base64编码
        param: {
          sql: Base64.encode(this.sqlString),
          ds_code: this.sourceData.code
        }
      })
        .then(res => {
          this.executeSqlString = this.sqlString;
          this.sourceId = this.sourceData.id;
          var model = res.data.model;
          if ($.isArray(model)) model = model[0];
          if (
            (!model.fields || !model.fields.length) &&
            res.data.data &&
            res.data.data.length
          ) {
            model.fields = [];
            for (let i in res.data.data[0]) {
              model.fields.push({
                code: i,
                name: i
              });
            }
          }
          this.$set(this, "resultModel", model);
          this.$set(this, "resultData", res.data.data);
        })
        .finally(() => {
          this.executing = false;
        });
    },
    exportConfirm() {
      return new Promise((resolve, reject) => {
        this.$Modal.confirm({
          title: "确认操作",
          content: this.confirmText(),
          onOk: () =>
            this.exportData()
              .then(res => {
                resolve(res);
              })
              .catch(res => {
                reject(res);
              }),
          onCancel() {
            resolve();
          }
        });
      });
    },
    fetchPreset() {
      this.presetIndex = null;
      $.link(this.path.preset.list, {}).then(res => {
        var data = res.data.data || res.data;
        this.$set(this, "presetList", data);
      });
    },
    savePreset() {
      var data = {};
      if (this.presetIndex) {
        data = {
          ...this.presetList[this.presetIndex]
        };
      }
      data.code = this.sqlString;
      data.name = this.sqlName;
      $.link(this.path.preset.save, data).then(res => {
        this.fetchPreset();
        this.$Notice.success({
          title: "数据保存成功"
        });
      });
    },
    deletePreset(id) {
      $.link(this.path.preset.delete, [id]).then(res => {
        this.$Notice.success({
          title: "数据删除成功"
        });
        this.fetchPreset();
      });
    },
    exportData() {
      var data = {};
      var rows = this.$refs.dataTable.getSelectedIds();
      data.param = {
        sql: Base64.encode(this.executeSqlString),
        ds_code: this.sourceData.code
      };
      if (rows && rows.length) {
        data.rows = rows;
      }
      this.exportLoading = true;
      return $.download(this.path.export, data)
        .then(res => {
          this.actionSuccess();
        })
        .finally(() => {
          this.exportLoading = false;
        });
    },
    confirmText() {
      var count = this.$refs.dataTable.totalCount;
      var text = "";
      var rows = this.$refs.dataTable.getSelectedIds();
      if (rows && rows.length) {
        count = rows.length;
        text = "确认导出当前选中的" + count + "条数据";
      } else {
        if (count) {
          text = "确认导出当前过滤的" + count + "条数据";
        } else {
          text = "确认导出当前过滤的数据";
        }
      }
      return text;
    },
    clearSql() {
      this.sqlString = "";
    },
    openSqlList() {},
    saveSql() {},
    sourceChange(data) {
      this.sourceData = data;
      this.fetchEntity(this.sourceData.code);
    },
    //查询实体
    fetchEntity(code) {
      $.link(this.path.entity, null, {
        param: {
          code
        }
      }).then(res => {
        this.entityCode = null;
        this.$set(this, "entityList", res.data);
      });
    },
    //选择实体变化 暂时无用
    entityChange(index) {
      this.entityCode =
        this.entityList[index] && this.entityList[index].TABLE_NAME;
    },
    //选中加载·一个预置选项
    selectpresetList(index) {
      this.presetIndex = index;
      this.sqlName = this.presetList[this.presetIndex].name;
      this.sqlString = this.presetList[this.presetIndex].code;
      this.presetVisible = false;
    }
  },
  created() {
    //this.fetchPreset();
  },
  directives: {
    HeightLight,
    ClickOut
  },
  components: {
    Selector,
    SelectPanel,
    CodeEditor,
    DataTable,
    GridPanel,
    Modal
  }
};
</script>

<style lang="less">
.node-db-console {
  height: 100%;
  .preset-select {
    border-left: 6px solid #2d8cf0;
  }
  .name-input {
    margin-bottom: 12px;
    .ivu-input-group-prepend {
      padding: 0 16px;
    }
  }
  .item-name {
    padding-right: 12px;
    .pull-right {
      margin-right: -16px;
    }
  }

  .ivu-row-flex {
    height: 100%;
  }
  .ivu-btn {
    margin-right: 4px;
    &.pull-right {
      margin-left: 4px;
      margin-right: 0;
    }
  }
  .left-box {
    padding-right: 8px;
  }
  .right-box {
    padding-left: 8px;
    border-left: 1px solid #ddd;
  }
  .CodeMirror {
    height: 106px;
  }
  hr {
    margin: 8px 0;
  }
  .item-code {
    padding: 8px;
  }
  .entity-option {
    word-break: break-word;
    .type-code {
      color: #c1c1c1;
      float: right;
    }
  }
}
</style>
